<?php
namespace frontend\controllers;

use yii\captcha\CaptchaValidator;
use yii\filters\VerbFilter;
use Yunpian\Sdk\YunpianClient;




/**
 * Util controller
 * 公共业务流程的控制器
 */
class UtilController extends BaseMobileController
{


    public $layout = false;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'sms-code' => ['post'],
                ],
            ],
        ];
    }




    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                //'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
                //'backColor'=>0x000000,//背景颜色
                'maxLength' => 4, //最大显示个数
                'minLength' => 4,//最少显示个数
                //'padding' => 5,//间距
                'height'=>30,//高度
                'width' => 50,  //宽度
                // 'foreColor'=>0xffffff,     //字体颜色
                //'offset'=>4,        //设置字符偏移量 有效果
                //'controller'=>'login',        //拥有这个动作的controller
            ],
        ];
    }



    /**
     * 获取短信验证码
     */
    public function actionSmsCode()
    {
        $code = rand(10000,99999);
        $postdata = \Yii::$app->request->post();
        $caprcha = new CaptchaValidator();
        if(!$this->createAction('captcha')->validate($postdata['pcode'], false)){
            return \GuzzleHttp\json_encode(['msg'=>'图形验证码有误','status'=>1]);
        }


        //初始化client,apikey作为所有请求的默认值
        $clnt = YunpianClient::create('007cd011067a796fb688cef1473dbf7e');
        \Yii::$app->session->set('smscode',$code);
        if(empty($this->user['nickname'])){
            $this->user['nickname'] = '用户';
        }
        $param = [YunpianClient::MOBILE => $postdata['tel'],YunpianClient::TEXT => '【牧心农业】亲爱的'.$this->user['nickname'].'，您的验证码是'.$code.'。有效期为20分钟，请尽快验证。'];
        $r = $clnt->sms()->single_send($param);
        return json_encode(['msg'=>'短信发送成功','status'=>0]);

    }
}
